<template>
  <div class="" v-on:click.self="unSelect" style="height:100%;">
    <div class="opt">
      <span @click="state=1"><i class="fa fa-plus"></i>添加磁贴</span>
      <span v-if="status=='edit' || status=='add'" @click="status==='edit'?editSave():save()"><i class="fa fa-floppy-o" aria-hidden="true"></i>保存</span>
    </div>
    <template v-if="status=='edit' || status=='add'">
      <div style="width:calc(100% - (180px) * 2);height:calc(100% - 50px);float: left;">
        <report-canvas class="report-canvas displayArea" :list="canvasItems" @select="canvasItemSelect" :currentEditIndex='currentEditIndex' :status="status" :resizable="status=='edit' || status=='add'" :draggable="status=='edit' || status=='add'" ref="canvas"></report-canvas>
      </div>
    </template>
    <template v-else>
      <div style="width:100%;height:100%;padding:18px;box-sizing:border-box">
        <report-canvas class="report-canvas  view" :list="canvasItems" @select="canvasItemSelect" :currentEditIndex='currentEditIndex' :status="status" :resizable="status=='edit' || status=='add'" :draggable="status=='edit' || status=='add'" ref="canvas"></report-canvas>
      </div>
    </template>
    <el-dialog title="获取数据源" custom-class="data-select-dialog" :visible="state==1" :show-close="false">
      <div style="padding:20px;">
        <el-button @click="state=2" type="success" style="width:100%;margin-bottom:20px;">添加数据流</el-button>
        <!-- 步骤一 -->
        <el-form ref="form" :model="form" label-position="top" style="padding:20px;background:#fff;min-height:200px;margin-bottom:20px;">
          <el-form-item label="我的数据流">
            <el-select v-model="form.id" placeholder="请选择">
              <el-option v-for="item in myDataFlows" :key="item.value" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="next">下一步</el-button>
            <el-button @click="state=0">取消</el-button>
          </el-form-item>
        </el-form>
        <el-button type="text" size="small" @click="state=4">管理数据流</el-button>
      </div>
    </el-dialog>
    <el-dialog title="获取数据源" custom-class="data-select-dialog" :visible="state==5" :show-close="false">
      <div style="padding:20px;">
        <el-button @click="state=2" type="success" style="width:100%;margin-bottom:20px;">添加数据流</el-button>
        <!-- 步骤二 -->
        <el-form ref="form" :model="form" label-position="top" style="padding:20px;background:#fff;min-height:200px;margin-bottom:20px;">
          <el-form-item label="可视化类型效果">
            <el-select v-model="form.type" placeholder="请选择">
              <el-option v-for="item in 3" :key="item" :label="item|dataFlowChart" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="字段">
            <el-row v-for="(item,index) in form.fields" style="margin-bottom: 10px;">
              <el-col :span="23">
                <el-select v-model="item.type" style="width: 100%;">
                  <el-option v-for="ii in selectedFields" :key="ii.name" :label="ii.name" :value="ii.name">
                  </el-option>
                </el-select>
              </el-col>
              <el-col v-show="form.fields.length>1" class="line" :span="1"><i @click="form.fields.splice(index,1)" class="fa fa-trash-o"></i></el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-button type="text" size="small" @click="form.fields.push({type:''})">添加字段</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addCard">立即创建</el-button>
            <el-button @click="state=0">取消</el-button>
          </el-form-item>
        </el-form>
        <el-button type="text" size="small" @click="state=4">管理数据流</el-button>
      </div>
    </el-dialog>
    <el-dialog title="创建数据流" custom-class="data-select-dialog" :visible="state==2" :show-close="false">
      <div style="padding:20px;">
        <el-button type="text" size="small" @click="state=1"><i class="fa fa-angle-double-left"></i>返回</el-button>
        <el-form ref="form" :model="formDataflow" label-position="top" style="padding:20px;background:#fff;min-height:200px;margin-bottom:20px;">
          <el-form-item label="数据流名称">
            <el-input type="text" v-model="formDataflow.name">
            </el-input>
          </el-form-item>
          <el-form-item label="流中的值">
            <el-row v-for="(item,index) in formDataflow.content" style="margin-bottom: 10px;">
              <el-col :span="11">
                <el-select v-model="item.type" style="width: 100%;">
                  <el-option v-for="ii in 3" :key="ii" :label="ii|dataFlowType" :value="ii">
                  </el-option>
                </el-select>
              </el-col>
              <el-col class="line" :span="1">&nbsp;</el-col>
              <el-col :span="11">
              </el-col>
              <el-col v-show="form.fields.length>1" class="line" :span="1"><i @click="form.fields.splice(index,1)" class="fa fa-trash-o"></i></el-col>
            </el-row>
          </el-form-item>
          <el-row :gutter="20" style="margin-bottom:20px;" v-show="dataFlowPreview">
            <el-col :span="24">
              <el-input type="textarea" :readonly="true" :rows="6" v-model="dataFlowPreview">
              </el-input>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="addDataFlow">创建</el-button>
            <el-button @click="state=1">取消</el-button>
          </el-form-item>
        </el-form>
        <el-button type="text" size="small" @click="state=4">管理数据流</el-button>
      </div>
    </el-dialog>
    <el-dialog title="创建数据流" custom-class="data-select-dialog" :visible="state==3" :show-close="false">
      <div style="padding:20px;">
        已创建 {{formDataflow.name}} 的架构。
        <p>推送 URL</p>
        <el-input :readonly="true" type="text" v-model="dataflowUrl"></el-input>
        <el-tabs v-model="activeTagName" style="margin-bottom:20px;">
          <el-tab-pane label="Raw" name="a">
            <el-input type="textarea" :readonly="true" :rows="6" v-model="dataFlowPreview">
            </el-input>
          </el-tab-pane>
        </el-tabs>
        <el-button type="primary" @click="state=1">完成</el-button>
      </div>
    </el-dialog>
    <el-dialog title="管理数据流" :visible="state==4" :show-close="false">
      <el-button type="text" size="small" @click="state=1"><i class="fa fa-angle-double-left"></i>返回</el-button>
      <el-table :data="myDataFlows" style="width: 100%" max-height="250">
        <el-table-column prop="name" label="名称">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <i class="fa fa-eye" @click="viewDataFlow(scope.$index)"></i>
            <i class="fa fa-trash-o" @click="editDataFlow(scope.$index)"></i>
            <i class="fa fa-pencil-square-o" @click="delDataFlow(scope.$index)"></i>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import http from 'assets/js/http'
import fomrMixin from 'assets/js/form_com'
import trans from 'assets/js/trans'

export default {
  data() {
      return {
        isLoading: false,
        state: 0, //0无弹窗，1创建磁贴，2创建数据流，3创建数据流完成，4管理数据流，5创建此贴第二步
        activeTagName: 'a',
        myDataFlows: [],
        form: {
          id: '',
          type: 1,
          fields: [{
            type: ''
          }]
        },
        formDataflow: {
          name: '',
          content: [{
            name: '',
            type: ''
          }]
        },
        dataflowUrl: '', //推送地址
        report: '', //报表详情
        datas: [], //所有数据集
        dataCheckList: [], //包含的数据集id，多个用逗号隔开
        currentDataId: '',
        rules: {
          name: [{
            required: true,
            message: '请输入报表标题'
          }],
        },
        currentEditIndex: '', //画布当前选中项下标
        canvasItems: [], //画布视觉组件列表
        dragObj: '', //当前拖动的数据列对象
      }
    },
    computed: {
      id: function() {
        return this.$route.params.id
      },
      status: function() {
        if (this.$route.path.indexOf('add') > -1) {
          return 'add'
        } else if (this.$route.path.indexOf('edit') > -1) {
          return 'edit'
        }
        if (this.$route.path.indexOf('view') > -1) {
          return 'view'
        }
      },
      dataSelect: function() {
        let data = this.datas.filter((n) => _.indexOf(this.dataCheckList, n.id) > -1)
        data.forEach((n) => {
          let theads = []
          let data = trans.str2HotData(n.content)
          for (let i = 0; i < data[0].length; i++) {
            if ((typeof data[0][i] == 'string') && data[0][i].constructor == String && data[0][i].length) {
              theads.push(data[0][i])
            }
          }
          n.theads = theads
        })
        return data
      },
      canvasItem: function() {
        return this.currentEditIndex >= 0 ? this.canvasItems[this.currentEditIndex] : ''
      },
      dataFlowPreview: function() {
        let datas = this.formDataflow.content.filter((n) => n.name.length > 0)
        if (!datas.length) {
          return ''
        }
        let arr = []
        for (let i = 0; i < datas.length; i++) {
          let item = datas[i]
          let str = ''
          switch (item.type) {
            case 1:
              str = '"' + item.name + '" :"AAAAA555555"';
              break;
            case 2:
              str = '"' + item.name + '" :98.6';
              break;
            case 3:
              let date = moment(new Date().getTime()).format('YYYY-MM-DD H:mm:ss')
              str = '"' + item.name + '" :"' + date + '"';
              break;
          }
          str = '\t\t' + str
          arr.push(str)
        }
        return ['[', '\t{'].concat([arr.join(',\n')]).concat(['\t}', ']']).join('\n')
      },
      selectedFields: function() {
        let that = this
        let selectedDataflow = this.myDataFlows.find((n) => n.id == that.form.id)
        if (!selectedDataflow) {
          return ''
        }
        let content = selectedDataflow.content
        let fields = JSON.parse(content)
        return fields
      },
    },
    methods: {
      viewDataFlow(index) {

      },
      editDataFlow(index) {

      },
      delDataFlow(index) {

      },
      setDataflowContentLength(v, isLast) {
        if (v.length && isLast) {
          this.formDataflow.content.push({
            name: '',
            type: 1
          })
        }
      },
      addDataFlow() {
        let that = this
        let data = {
          name: that.formDataflow.name,
          content: JSON.stringify(that.formDataflow.content.filter((n) => n.name.length > 0))
        }
        this.apiPost('/admin/dataflows', data).then(function(res) {
          if (res.code === 200) {
            /*这里做处理*/
            window.console && console.log(res);
            _g.toastMsg('success', '添加成功')
            that.dataflowUrl = '' + res.data
            that.state = 3
            that.getDataFlow()
          }
        })
      },
      next() {
        this.state = 5
      },
      findPosition() {
        let positions = [
          [0, 0],
          [0, 200],
          [200, 0],
          [200, 200],
          [400, 0],
          [400, 200]
        ]
        for (let i = 0; i < positions.length;) {
          let used = this.canvasItems.find((n) => n.x == positions[i][0] && n.y == positions[i][1])
          if (used) {
            i++
          } else {
            return positions[i]
          }
        }
        return [100, 100]
      },
      getChartType(v) {
        let charts = [{
          "name": "卡片",
          "type": "highchart",
          "width": 200,
          "height": 200
        }, {
          "name": "曲线图",
          "type": "highchart",
          "typesFile": "2.1",
          "className": "lineChart",
          "width": 200,
          "height": 200
        }, {
          "name": "仪表盘",
          "type": "highchart",
          "typesFile": "1.1",
          "width": 200,
          "height": 200
        }]
        return charts[v - 1]
      },
      addCard() {
        let that = this

        let x, y
        let positions = this.findPosition()
        let chart = this.getChartType(this.form.type)
        this.canvasItems.push({
          x: positions[0],
          y: positions[1],
          axis: [],
          value: [],
          chart: chart,
          form: this.form
        })

        this.form = {
          id: '',
          type: 1,
          fields: [{
            type: ''
          }]
        }
        this.state = 0
      },
      save() {
        let that = this
        let canvasItems = this.canvasItems
        canvasItems = JSON.stringify(canvasItems)
          // Lockr.set('canvasItems', canvasItems)
          // window.console && console.log(canvasItems);

        let datas = this.datas
        datas = JSON.stringify(datas)
          // Lockr.set('datas', datas)
          // window.console && console.log(datas);

        let dataCheckList = this.dataCheckList
        dataCheckList = JSON.stringify(dataCheckList)
          // Lockr.set('dataCheckList', dataCheckList)
          // window.console && console.log(dataCheckList);

        let content = {
          canvasItems: canvasItems,
          datas: datas,
          dataCheckList: dataCheckList,
        }

        this.$prompt('请输入报表名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '名称格式不正确'
        }).then((value) => {

          let data = {
            name: value.value,
            content: JSON.stringify(content),
          }

          this.apiPost('/admin/reports', data).then(function(res) {
            if (res.code === 200) {
              /*这里做处理*/
              window.console && console.log(res);
              _g.toastMsg('success', '添加成功')
              setTimeout(() => {
                that.goback()
              }, 1500)
            }
          })

        }).catch(() => {

        });


      },
      editSave() {
        let that = this
        let canvasItems = this.canvasItems
        canvasItems = JSON.stringify(canvasItems)
        let datas = this.datas
        datas = JSON.stringify(datas)
        let dataCheckList = this.dataCheckList
        dataCheckList = JSON.stringify(dataCheckList)

        let content = {
          canvasItems: canvasItems,
          datas: datas,
          dataCheckList: dataCheckList,
        }

        this.$prompt('请输入报表名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '名称格式不正确',
          inputValue: that.report.name,
        }).then((value) => {

          let data = {
            name: value.value,
            content: JSON.stringify(content),
          }

          this.apiPut('/admin/reports/', this.id, data).then(function(res) {
            if (res.code === 200) {
              /*这里做处理*/
              window.console && console.log(res);
              _g.toastMsg('success', '修改成功')
              setTimeout(() => {
                that.goback()
              }, 1500)
            }
          })

        }).catch(() => {

        });


      },
      unSelect(e) {
        // 点击无效
        // window.console && console.log('unSelect')
        // this.currentEditIndex = ''
      },
      add(form) {
        this.$refs.form.validate((pass) => {
          if (pass) {
            this.isLoading = !this.isLoading
            this.apiPost('admin/reports', this.form).then((res) => {
              this.handelResponse(res, (data) => {
                _g.toastMsg('success', '添加成功')

                // 删除旧数据源
                this.apiDelete('admin/reportDatas/deleteByReportId', this.reportId).then((res) => {
                  this.handelResponse(res, (data) => {

                    // 新增数据源
                    let model = {
                      report_id: data.id,
                      data_idL: this.dataId,
                    }
                    this.apiPost('admin/reportDatas/', model).then((res) => {
                      this.handelResponse(res, (data) => {

                      }, () => {
                        setTimeout(() => {
                          this.goback()
                        }, 1500)
                      })
                    })

                  })
                })

              }, () => {
                this.isLoading = !this.isLoading
              })
            })

          }
        })
      },
      fecthDatas() {
        if (this.status === 'edit' || this.status === 'view') {

          this.apiGet('admin/reports/' + this.id).then((res) => {
            this.handelResponse(res, (data) => {
              let report = data
              let content = JSON.parse(report.content)
              window.console && console.log(content);
              if (content) {
                this.datas = JSON.parse(content.datas)
                this.dataCheckList = JSON.parse(content.dataCheckList)
                this.canvasItems = JSON.parse(content.canvasItems)
              }
              this.report = report
            })
          })
        } else {
          this.apiGet('admin/datas').then((res) => {
            this.handelResponse(res, (data) => {
              this.datas = data
            })
          })
        }

        this.getDataFlow()
      },
      getDataFlow() {
        //获取数据集
        this.apiGet('admin/dataflows/').then((res) => {
          this.handelResponse(res, (data) => {
            this.myDataFlows = data
          })
        })
      },
      dataSlect(id) {
        this.currentDataId = id
      },
      selectData() {
        this.dialogGetDataSourceVisible = false
        this.dataCheckList = this.$refs.dataList.checkList
          // this.fecthDatas()
      },
      findPosition() {
        let positions = [
          [0, 0],
          [0, 200],
          [200, 0],
          [200, 200],
          [400, 0],
          [400, 200]
        ]
        for (let i = 0; i < positions.length;) {
          let used = this.canvasItems.find((n) => n.x == positions[i][0] && n.y == positions[i][1])
          if (used) {
            i++
          } else {
            return positions[i]
          }
        }
        return [100, 100]
      },
      chartSlect(chart) {
        if (this.currentEditIndex === '') { //添加报表
          let x, y
          let positions = this.findPosition()
          this.canvasItems.push({
            x: positions[0],
            y: positions[1],
            axis: [],
            value: [],
            chart: chart
          })
          this.currentEditIndex = this.canvasItems.length - 1
        } else if (chart) { //切换报表类型
          window.console && console.log('切换报表类型');
          this.canvasItems[this.currentEditIndex].chart = chart
        } else { //取消选择
          this.currentEditIndex = ''
        }
      },
      canvasItemSelect(index) {
        if (this.status === 'edit' || this.status === 'add') {
          this.currentEditIndex = index
        }
      },
      datasChanged(value) {
        // let editIndex = this.currentEditIndex
        // if (editIndex === '') {
        //   let chart = this.$refs.chartSelect.charts.find((n) => n.type == 'table')
        //   this.canvasItems.push({
        //     chart: chart,
        //     axis: [],
        //     value: [],
        //   })
        //   this.currentEditIndex = this.canvasItems.length - 1
        // }
        // this.canvasItems[this.currentEditIndex].data = value
      },
      dataChanged(check) {
        window.console && console.log(check);
      },
    },
    created() {
      window.console && console.log(22);
      this.fecthDatas()
    },
    components: {
      dataEdit: resolve => require(['../data/edit.vue'], resolve),
      reportCanvas: resolve => require(['./reportCanvas.vue'], resolve),
      datasList: resolve => require(['../data/list.vue'], resolve),
    },
    mixins: [http, fomrMixin]
}
</script>
<style lang="less" scope>
.data-select-dialog {
  background: #EAEAEA;
  .el-dialog__header {
    background: #fff;
    height: 40px;
  }
  .el-dialog__body {
    padding: 0
  }
}

.displayArea {
  margin: 0;
  width: 100%;
  height: 100%;
  position: absolute;
  box-shadow: 0 0 10px #C8C8C8;
  background-color: #FFF;
  box-sizing: border-box;
  overflow: hidden;
  transform-origin: center;
  -webkit-transform-origin: center;
  top: 50%;
  left: 50%;
  margin-left: -536.444px;
  margin-top: -210.5px;
  width: 712.889px;
  height: 421px;
}

.view {
  width: 100%;
  height: 100%;
  position: relative;
  box-shadow: 0 0 10px #C8C8C8;
  background-color: #FFF;
  box-sizing: border-box;
  overflow: hidden;
  transform-origin: center;
  -webkit-transform-origin: center;
}
</style>
<style lang="less">
.ctx-menu {
  li {
    padding-left: 40px;
  }
}

.paneHeader {
  box-sizing: border-box;
  height: 48px;
  padding-bottom: 20px;
  background-color: #212121;
  h2 {
    margin: 0;
    font-weight: normal;
    font-size: 18px;
    line-height: 50px;
    padding: 0 20px
  }
}

.sidePane {
  background: #444;
  z-index: 4;
  height: calc(~"100% - 40px");
  color: #FFF;
  float: right;
  overflow: hidden;
}

.sidePaneHorizontalTitle {
  margin: 16px 0 0 12px;
  line-height: 16px;
  float: none;
  cursor: pointer;
  width: auto;
  text-align: left;
}

.opt {
  text-align: right;
  padding: 0 2em;
  span {
    color: #333;
    cursor: pointer;
    font-size: 13px;
    display: inline-block;
    vertical-align: top;
    line-height: 40px;
    padding: 0 10px;
    outline: 0;
    &:hover {
      background-color: #C8C8C8;
    }
    i {
      font-size: 15px;
      margin: 0 8px;
    }
  }
}

.fa-trash-o {
  margin-left: 10px;
  color: #c3c1c1;
}
</style>
